import { defineStore } from 'pinia'
import { computed, ref } from 'vue'

function createTokenStore(storageKey) {
    const token = ref(localStorage.getItem(storageKey) || '')

    const setToken = (newToken) => {
        token.value = newToken
        localStorage.setItem(storageKey, newToken)
    }

    const removeToken = () => {
        token.value = ''
        localStorage.removeItem(storageKey)
    }

    // 检查 token 是否过期的工具函数（提取出来复用）
    const checkTokenExpired = () => {
        if (!token.value) return true
        if (token.value.includes('.')) {
            try {
                const payload = JSON.parse(atob(token.value.split('.')[1]))
                const currentTime = Math.floor(Date.now() / 1000)
                return payload.exp ? payload.exp < currentTime : true
            } catch (e) {
                return true
            }
        }
        return false
    }

    const hasToken = computed(() => {
        // 先检查是否存在有效 token
        if (!token.value || token.value === null) {
            return false
        }
        // 检查是否过期，如果过期则移除
        if (checkTokenExpired()) {
            removeToken()
            return false
        }
        // 存在且未过期
        return true
    })

    // 保留独立的过期检查属性（如需单独使用）
    const isTokenExpired = computed(() => checkTokenExpired())

    return {
        token,
        setToken,
        removeToken,
        hasToken,
        isTokenExpired
    }
}

export const userTokenStore = defineStore('token', () => createTokenStore('user_token'), {
    persist: true
})

export const adminTokenStore = defineStore('adminToken', () => createTokenStore('admin_token'), {
    persist: true
})